// src/utils/request.js
import axios from 'axios'
import { ElMessage } from 'element-plus'

// 创建axios实例
const request = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL || 'http://localhost:3001/api',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  },
  withCredentials: true  // 🔥 开启凭据传递
})

// 请求拦截器
request.interceptors.request.use(
  config => {
    // 添加认证token
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    
    // 🔥 简化请求ID，避免特殊字符
    config.headers['x-request-id'] = `req_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
    
    console.log('🚀 发起请求:', {
      url: config.url,
      method: config.method?.toUpperCase(),
      headers: config.headers,
      data: config.data
    })
    
    return config
  },
  error => {
    console.error('❌ 请求错误:', error)
    return Promise.reject(error)
  }
)

// 响应拦截器
request.interceptors.response.use(
  response => {
    console.log('✅ 响应成功:', response.config.url, response.status)
    return response.data
  },
  error => {
    console.error('❌ 响应错误:', error)
    
    // 🔥 特别处理CORS错误
    if (error.message?.includes('CORS') || error.message?.includes('Network Error')) {
      ElMessage.error('网络连接错误，请检查服务器状态')
      return Promise.reject(error)
    }
    
    const { status, data } = error.response || {}
    
    switch (status) {
      case 401:
        ElMessage.error('未授权，请重新登录')
        localStorage.clear()
        window.location.href = '/auth/login'
        break
      case 403:
        ElMessage.error('权限不足')
        break
      case 404:
        ElMessage.error('请求的资源不存在')
        break
      case 500:
        ElMessage.error('服务器内部错误')
        break
      default:
        ElMessage.error(data?.message || error.message || '网络错误')
    }
    
    return Promise.reject(error)
  }
)

export default request